<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="元器件类型id" prop="typeId">-->
<!--        <el-input-->
<!--          v-model="queryParams.typeId"-->
<!--          placeholder="请输入元器件类型id"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="元器件类型名称" prop="typeName">-->
<!--        <el-input-->
<!--          v-model="queryParams.typeName"-->
<!--          placeholder="请输入元器件类型名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="预处理数据集对应的id" prop="componentdataId">-->
<!--        <el-input-->
<!--          v-model="queryParams.componentdataId"-->
<!--          placeholder="请输入预处理数据集对应的id"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="工况id" prop="conditionsId">
        <el-input
          v-model="queryParams.conditionsId"
          placeholder="请输入工况id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bearing:pretreatment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bearing:pretreatment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button 
          type="primary" 
          plain 
          size="mini"
          @click="showDesc = !showDesc"
          v-show=" pretreatmentDataPageAll.length != 0"
        >
          {{ showDesc ? '显示预处理数据' : '显示原始数据' }}
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 修改后的表格/图表展示区域 -->
    <template v-if="pretreatmentDataPage.rows && pretreatmentDataPage.rows.length && !showDesc">
      <el-row class="mb8">
        <el-col :span="1.5">
          <el-button 
            type="primary" 
            plain 
            @click="showChart = !showChart"
          >
            {{ showChart ? '切换表格' : '切换图表' }}
          </el-button>
        </el-col>
      </el-row>

      <template v-if="!showChart && !showDesc">
        <el-table 
          v-loading="loading" 
          :data="pretreatmentDataPage.rows" 
          style="width: 100%"
        >
          <el-table-column 
            v-for="(value, key) in pretreatmentDataPage.rows[0]" 
            :key="key"
            :prop="key" 
            :label="key"
            align="center"
          />
        </el-table>

        <pagination
          v-show="pretreatmentDataPage.total>0"
          :total="pretreatmentDataPage.total"
          :page.sync="pretreatmentDataPage.pageNum"
          :limit.sync="pretreatmentDataPage.pageSize"
          @pagination="getPretreatmentDataPage"
        />
      </template>

      <div v-else ref="chartContainer" style="height: 600px; width: 100%"></div>
    </template>

    <!-- 原有表格作为缺省展示 -->
    <template v-else>
      <el-table v-loading="loading" :data="pretreatmentList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column label="数据集名称" align="center" prop="componentdataName" />
        <el-table-column label="元器件类型名称" align="center" prop="typeName" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_type" :value="scope.row.typeName"/>
          </template>
        </el-table-column>
        <el-table-column label="预处理后文件地址" align="center" prop="pretreatmentFile" />
        <el-table-column label="预处理数据集对应的id" align="center" prop="componentdataId" />
        <el-table-column label="工况id" align="center" prop="conditionsId" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="loadPretreatmentData(scope.row.pretreatmentFile)"
              v-hasPermi="['bearing:pretreatment:edit']"
            >加载预处理数据</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['bearing:pretreatment:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </template>

    <!-- 添加或修改数据预处理对话框 -->
    <el-dialog 
      :title="title" 
      :visible.sync="open" 
      width="600px" 
      append-to-body 
      :close-on-click-modal="false" 
      :close-on-press-escape="false"
      @close="cancel"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="预处理数据集" prop="componentdataId">
          <el-select v-model="form.componentdataId" placeholder="请输入预处理数据集" @change="checkDataset" style="width: 100%">
            <el-option
              v-for="item in componentdataOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工况id" prop="conditionsId">
          <el-input v-model="form.conditionsId" placeholder="请输入工况id" style="width: 100%"  disabled/>
        </el-form-item>
        <!-- <el-form-item label="元器件类型id" prop="typeId">
          <el-input v-model="form.typeId" placeholder="请输入元器件类型id" style="width: 100%" />
        </el-form-item> -->
        <el-form-item label="元器件类型名称" prop="typeName">
          <el-input v-model="form.typeName" placeholder="请输入元器件类型名称" style="width: 100%" disabled/>
        </el-form-item>
        <el-form-item label="预处理后文件地址" prop="pretreatmentFile" >
          <div style="display: flex;align-items: center;">
            <el-input v-model="form.pretreatmentFile" placeholder="请输入预处理后文件名称" style="width: 100%" />
          <el-input v-model="pretreatmentFileSuffix" style="width: 60px" disabled/>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>




  </div>
</template>

<script>
import { readAndStoreExcelDataToRedis,listPretreatment, getPretreatment, delPretreatment, addPretreatment, updatePretreatment, getPretreatmentDataPageAll, getPretreatmentDataPage } from "@/api/bearing/pretreatment";
import { selectAll } from "@/api/bearing/componentdata";
import * as echarts from "echarts";
export default {
  name: "Pretreatment",
  dicts: ['sys_type', 'sys_four'],
  data() {
    return {
      pretreatmentFileSuffix: '.xlsx',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据预处理表格数据
      pretreatmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeId: null,
        typeName: null,
        pretreatmentFile: null,
        componentdataId: null,
        conditionsId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        componentdataId: [
          { required: true, message: "请选择预处理数据集", trigger: "change" }
        ],
        conditionsId: [
          { required: true, message: "请输入工况id", trigger: "change" }
        ],
        typeName: [
          { required: true, message: "请选择元器件类型", trigger: "change" }
        ],
        pretreatmentFile: [
          { required: true, message: "请输入预处理后文件名称", trigger: "blur" }
        ]
      },
      componentdataOptions:[],
      pretreatmentDataPageAll:[],
      pretreatmentDataPage:{
        rows:[],
        total:0,
        pageNum:1,
        pageSize:10
      },
      showChart: false,
      showDesc: false,
      chart: null,
      colorPalette: [
        '#5470C6', '#91CC75', '#FAC858', '#EE6666', 
        '#73C0DE', '#3BA272', '#FC8452', '#9A60B4'
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    loadPretreatmentData(path){
      readAndStoreExcelDataToRedis(path).then(response => {
        this.$modal.msgSuccess("加载成功");
        this.getPretreatmentDataPageAll();
        this.getPretreatmentDataPage();
      }).catch(() => {
        this.$modal.msgError("加载失败");
      });
    },
    /**
     * 查询所有数据预处理信息
     */
    getPretreatmentDataPageAll(){
      this.loading = true;
      getPretreatmentDataPageAll().then(response => {
        this.pretreatmentDataPageAll = response.data.data;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      }); 
    },
    /**
     * 分页查询所有数据预处理信息
     */
    getPretreatmentDataPage(){
      this.loading = true;
      this.pretreatmentDataPage.rows = [];
      this.pretreatmentDataPage.total = 0;
      getPretreatmentDataPage(this.pretreatmentDataPage).then(response => {
        this.pretreatmentDataPage.rows = response.data.data;
        this.pretreatmentDataPage.total = response.data.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    checkDataset(id){
      
      this.form.componentdataId = id
      this.form.componentdataName = this.componentdataOptions.find(item => item.id === id).name
      this.form.typeName = this.componentdataOptions.find(item => item.id === id).typeName
      this.form.conditionsId = this.componentdataOptions.find(item => item.id === id).conditionId
      
      this.form.typeName = this.dict.type.sys_type[this.form.typeName].raw.dictLabel
    },
    /** 查询数据预处理列表 */
    getList() {
      this.loading = true;
      listPretreatment(this.queryParams).then(response => {
        this.pretreatmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        typeId: null,
        typeName: null,
        componentdataName: null,
        pretreatmentFile: null,
        componentdataId: null,
        conditionsId: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      // 查询所有数据集导入的数据
      this.getConponentdata()
      this.title = "添加数据预处理";
    },
    /**
     * 查询数据集导入的所有数据
     */
    getConponentdata() {
      
      if(this.componentdataOptions.length === 0){
        this.loading = true;
        selectAll().then(response => {
          this.componentdataOptions = response.data;
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.loading = true;
      getPretreatment(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据预处理";
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.loading = true;
            updatePretreatment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.loading = false;
            }).catch(() => {
              this.loading = false;
            });
          } else {
            this.form.pretreatmentFile = this.form.pretreatmentFile + this.pretreatmentFileSuffix
            this.loading = true;
            addPretreatment(this.form).then(response => {
              this.$modal.msgSuccess("处理成功");
              //  分页查询预处理后的数据
              this.getPretreatmentDataPage();
              //  查询所有预处理后的数据
              this.getPretreatmentDataPageAll();
              
              this.open = false;
              this.getList();
              this.loading = false;
            }).catch(() => {
              this.loading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除数据预处理编号为"' + ids + '"的数据项？').then(function() {
        return delPretreatment(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bearing/pretreatment/export', {
        ...this.queryParams
      }, `pretreatment_${new Date().getTime()}.xlsx`)
    },
    renderChart() {
      if (!this.pretreatmentDataPage.rows?.length) return;
      
      const chartDom = this.$refs.chartContainer;
      this.chart = echarts.init(chartDom);
      
      // 动态获取数据字段（排除时间字段）
      const keys = Object.keys(this.pretreatmentDataPage.rows[0])
        .filter(key => !['date', 'timeEpoch', 'nanosec_time'].includes(key))
        .sort(a => a === 'R_DS(on)' ? 1 : -1);

      // 提取时间数据
      const timeData = this.pretreatmentDataPage.rows.map(item => item.date);

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: keys,
          textStyle: {
            color: '#666'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: timeData,
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          }
        },
        dataZoom: [{
          type: 'inside',
          start: 0,
          end: 100,
          fillerColor: 'rgba(84,112,198,0.2)'
        }],
        series: keys.map((key, index) => {
          const color = this.colorPalette[index % this.colorPalette.length];
          
          return {
            name: key,
            type: 'line',
            smooth: true,
            symbol: 'none',
            sampling: 'lttb',
            lineStyle: {
              width: 2,
              color: color
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: color
                },
                {
                  offset: 1,
                  color: color + '00'
                }
              ])
            },
            data: this.pretreatmentDataPage.rows.map(item => item[key])
          };
        })
      };

      this.chart.setOption(option);
    }
  },
  watch: {
    showChart(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.renderChart();
        });
      }
    },
    'pretreatmentDataPage.rows': {
      handler() {
        if (this.showChart) {
          this.$nextTick(this.renderChart);
        }
      },
      deep: true
    }
  }
};
</script>
